package com.example.a2205douyin;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.a2205douyin.adapter.GiftAdapter;
import com.example.a2205douyin.adapter.MessageAdapter;
import com.example.a2205douyin.baseMVVM.view.BaseActivity;
import com.example.a2205douyin.databinding.ActivityLiveBinding;
import com.example.a2205douyin.db.Account;
import com.example.a2205douyin.db.AppDBUtils;
import com.example.a2205douyin.entity.GiftEntity;
import com.example.a2205douyin.entity.MessageEntity;
import com.example.a2205douyin.entity.ResultEntity;
import com.example.a2205douyin.entity.VideoEntity;
import com.example.a2205douyin.live.BaoCon;
import com.example.a2205douyin.live.GiftControl;
import com.example.a2205douyin.live.LiveViewModel;
import com.example.a2205douyin.pay.PayActivity;

import java.util.ArrayList;
import java.util.List;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import retrofit2.http.POST;
import top.littlefogcat.danmakulib.danmaku.Danmaku;
import top.littlefogcat.danmakulib.danmaku.DanmakuManager;

public class LiveActivity extends BaseActivity<ActivityLiveBinding, LiveViewModel> {
    VideoEntity.DataBean video;
    List<GiftEntity.DataBean> gifts = new ArrayList<>();
    GiftAdapter giftAdapter;
    Account account;//账户信息

    int index = -1;//礼物下标  为了防止未选中礼物就点击发送，导致有礼物发出的问题
    private GiftControl giftControl;
    private BaoCon baoCon;
    //烈焰弹幕使用  上下文   解析器
    private DanmakuContext danmakuContext;
    private BaseDanmakuParser baseDanmakuParser = new BaseDanmakuParser() {
        @Override
        protected IDanmakus parse() {
            return new Danmakus();
        }
    };

    List<MessageEntity> messages = new ArrayList<>();
    MessageAdapter messageAdapter;

    @Override
    protected void initData() {
        viewModel.guanSucc.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    binding.tvGuanzhu.setText("粉丝");
                    video.setGuanzhu(1);
                }
            }
        });
        viewModel.guanFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });

        viewModel.noguanSucc.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    binding.tvGuanzhu.setText("关注");
                    video.setGuanzhu(0);
                }
            }
        });
        viewModel.noguanFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
        viewModel.giftSucc.observe(this, new Observer<GiftEntity>() {
            @Override
            public void onChanged(GiftEntity entity) {
                if(entity.getCode()==200){
                    gifts.addAll(entity.getData());
                    giftAdapter.notifyDataSetChanged();
                }
            }
        });
        viewModel.giftFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
    }

    @Override
    protected void initView() {
        video = (VideoEntity.DataBean) getIntent().getExtras().get("video");
        //初始化视频播放器  用户信息
        initInfo();
        initGift();//初始化礼物
        initAccount();//初始化账户信息
        initDanmu();//初始化烈焰弹幕
        initMessage();//初始化消息列表
        giftControl = new GiftControl(binding.giftLayout,this);
        baoCon = new BaoCon(binding.baoLayout);
        //退出直播间
        binding.ivVideoClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //实现关注和取消关注
        binding.tvGuanzhu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(video.getGuanzhu()==1){
                    //执行取消关注操作
                    viewModel.noguanzhu(video.getAuthname()+"");
                }else{
                    //执行关注操作
                    viewModel.guanzhu(video.getAuthname()+"");
                }
            }
        });
        //给贝塞尔曲线添加图片
        binding.ksgview.addLikeImages(R.drawable.ic_xihuanred,R.drawable.ic_shoucangyellow,R.drawable.love_blue,R.drawable.love_green,R.drawable.love_yellow);
        //点赞，贝塞尔曲线效果
        binding.ivLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.ksgview.addFavor();//发送出图片
            }
        });
        //点击礼物图片，弹出礼物框
        binding.ivGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.clGift.setVisibility(View.VISIBLE);
            }
        });
        binding.ivGiftClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.clGift.setVisibility(View.GONE);
            }
        });
        //充值的点击事件
        binding.tvGoMoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到充值界面---预期结果  充值成功后，自动关闭充值界面，且当前界面余额更新
                //startActivity(new Intent(LiveActivity.this, PayActivity.class));
                Intent intent = new Intent(LiveActivity.this, PayActivity.class);
                startActivityForResult(intent,301);
            }
        });
        //点击礼物item,去选中要发送的礼物
        giftAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                Glide.with(LiveActivity.this).load(gifts.get(position).getGiftpath()).into(binding.ivGiftChecked);
                //记录当前选中的礼物下标
                index = position;
            }
        });
        //点击发送，实现发送礼物
        binding.ivGiftSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               if(index<0){
                   ToastUtils.showLong("您还未选中礼物哟");
                   return;
               }
               if(account.getMoney()<gifts.get(index).getPrice()){
                   ToastUtils.showLong("您的余额不足，请先去充值");
                   return;
               }
               //发送礼物，展示礼物动画
               sendGift();
               //一起展示礼物暴击效果
                giftControl.load(gifts.get(index));
                baoCon.load(gifts.get(index));
            }
        });
        //点击textView,弹出发送弹幕的输入框
        binding.tvMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.clEt.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(LiveActivity.this, R.anim.in);
                binding.clEt.startAnimation(animation);
            }
        });
        binding.etSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = binding.et.getText().toString().trim();
                if(trim.isEmpty()){
                    ToastUtils.showLong("您还未输入任何有效内容");
                    return;
                }
                //弹幕实体类
                Danmaku danmaku = new Danmaku();
                danmaku.text = trim;
                danmaku.size = 50;
                danmaku.color = Danmaku.COLOR_GREEN;
                //实现发送功能
                DanmakuManager.getInstance().init(LiveActivity.this,binding.viewDanmu);
                DanmakuManager.getInstance().send(danmaku);

                //发送烈焰弹幕
                binding.viewMaster.enableDanmakuDrawingCache(false);//是否开启缓存
                binding.viewMaster.removeAllDanmakus(true);//移除所有弹幕
                binding.viewMaster.clear();

                BaseDanmaku baseDanmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
                baseDanmaku.text = trim;
                baseDanmaku.textSize = 50;
                baseDanmaku.textColor = Color.YELLOW;
                baseDanmaku.borderColor = Color.RED;//边框颜色
                baseDanmaku.underlineColor = Color.GREEN;//下划线颜色
                baseDanmaku.setTime(800);
                binding.viewMaster.addDanmaku(baseDanmaku);
                binding.viewMaster.start();

                //展示到消息列表
                messages.add(new MessageEntity(SPUtils.getInstance().getString("username"),trim));
                messageAdapter.notifyDataSetChanged();
                binding.rvMessage.scrollToPosition(messages.size()-1);//滚动到最后一行



                //弹幕发送完成后，将输入框的内容进行清空，并且输入框隐藏
                binding.et.setText("");
                binding.clEt.setVisibility(View.GONE);

            }
        });
    }

    private void initMessage() {
        messageAdapter = new MessageAdapter(R.layout.item_message,messages);
        binding.rvMessage.setAdapter(messageAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setStackFromEnd(true);//从底部开始滚动
        binding.rvMessage.setLayoutManager(linearLayoutManager);

    }

    private void initDanmu() {
        //实例化上下文
        danmakuContext = DanmakuContext.create();
        binding.viewMaster.enableDanmakuDrawingCache(false);//是否开启缓存
        binding.viewMaster.removeAllDanmakus(true);//移除所有弹幕
        binding.viewMaster.clear();
        binding.viewMaster.prepare(baseDanmakuParser,danmakuContext);
    }

    ImageView iv;
    private void sendGift() {
        //弹出一个图片，展示动画效果，时间到了，图片消失
        if(iv==null){
            iv = new ImageView(this);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(500, 500);
            iv.setLayoutParams(params);//图片变成了一个边长为200的正方形
            Glide.with(this).load(gifts.get(index).getGiftpath()).into(iv);
            binding.clLive.addView(iv);
        }else{
            //第二次及以后发送时，图片已经存在，不需要实例化了，只需要让动画结束后隐藏的图片展示出来
            Glide.with(this).load(gifts.get(index).getGiftpath()).into(iv);
            iv.setVisibility(View.VISIBLE);
        }
        //iv展示动画效果 让图片从屏幕左侧移动到屏幕右侧
        //获取最右端的值
        int width = getWindowManager().getDefaultDisplay().getWidth();//屏幕的宽度
        int height = getWindowManager().getDefaultDisplay().getHeight();//屏幕的高度
        ObjectAnimator animator = ObjectAnimator.ofFloat(iv, "translationX", 0, width-200).setDuration(2000);
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(iv, "translationY", height/2-300, height/2-300).setDuration(2000);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(iv, "rotation", 0, 720).setDuration(2000);
        AnimatorSet set = new AnimatorSet();
        set.play(animator).with(animator1).with(animator2);
        set.addListener(new AnimatorListenerAdapter() {
            //当动画结束时---将图片隐藏
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                iv.setVisibility(View.GONE);
            }
            //当动画开始时，
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                //进行扣钱的操作
                account.setMoney(account.getMoney()-gifts.get(index).getPrice());
                AppDBUtils.getInstance().getAccountDao().updateAcc(account);
                //更新页面上的金额
                binding.tvAccount.setText(account.getMoney()+"元");
            }
        });
        set.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==301&&resultCode==302){
            //再次查询账户余额
            initAccount();
        }
    }

    private void initAccount() {
        //查询此账号是否存在
        account = AppDBUtils.getInstance().getAccountDao().queryByName(SPUtils.getInstance().getString("username"));
        if(account==null){
            //之前未创建过账号，，，，，新建账号
            account = new Account(SPUtils.getInstance().getString("username"),0);
            AppDBUtils.getInstance().getAccountDao().insertAcc(account);
        }
        //更新页面显示的余额
        binding.tvAccount.setText(account.getMoney()+"元");
    }

    private void initGift() {
        giftAdapter = new GiftAdapter(R.layout.item_gift,gifts);
        binding.rvGift.setAdapter(giftAdapter);
        binding.rvGift.setLayoutManager(new GridLayoutManager(this,4));
        viewModel.gift();
    }

    private void initInfo() {
        binding.gsy.setUp(video.getVideopath(),true,"");
        binding.gsy.getBackButton().setVisibility(View.GONE);
        binding.gsy.getStartButton().setVisibility(View.GONE);
        binding.gsy.startPlayLogic();

        Glide.with(this).load(video.getHeadpath()).circleCrop().into(binding.ivUser);//用户头像
        binding.tvUser.setText(video.getAuthname()+"");//用户名称
        //关注状态
        if(video.getGuanzhu()==1){
            //已关注，显示的是粉丝
            binding.tvGuanzhu.setText("粉丝");
        }else {
            //未关注，显示的是关注
            binding.tvGuanzhu.setText("关注");
        }

    }

    @Override
    protected Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_live;
    }
}